<template>
  <div class="cart">
    <div class="top">
      <span class="title"
        >购物车{{ cartList ? `(${cartList.valid.length})` : "" }}</span
      >
      <div
        class="rightBtn"
        v-if="cartList && cartList.valid.length > 0"
        @click="deleteFlag = !deleteFlag"
      >
        {{ deleteFlag ? "取消" : "管理" }}
      </div>
    </div>
    <van-pull-refresh
      v-model="isLoading"
      success-text="刷新成功"
      @refresh="onRefresh"
      class="content"
      v-if="cartList"
    >
      <van-collapse v-model="activeNames" v-if="cartList.invalid.length > 0">
        <van-collapse-item name="invalid" class="invalidList">
          <template #title>
            <div class="collapseTitle">
              {{ `失效商品(${cartList.invalid.length})` }}
              <van-icon name="warning-o" />
            </div>
          </template>
          <swiper :options="swiperOption_invalid" class="swiper">
            <swiper-slide v-for="item in cartList.invalid" :key="item.id">
              <div
                class="invalidItem"
                @click.stop="$router.push('/detail/' + item.productInfo.id)"
              >
                <div class="img">
                  <img :src="item.productInfo.image" />
                </div>
                <div class="info">
                  <div class="title">
                    {{ item.productInfo.store_name }}
                  </div>
                  <div class="info_b">
                    <div class="price">
                      ¥
                      <span>{{ item.productInfo.price | formatPrice(0) }}</span
                      >.{{ item.productInfo.price | formatPrice(1) }}
                    </div>
                    <div class="num">x{{ item.cart_num }}</div>
                  </div>
                </div>
              </div>
            </swiper-slide>
          </swiper>
        </van-collapse-item>
      </van-collapse>
      <van-empty
        v-if="cartList.valid.length == 0"
        description="购物车空空如也~"
      />
      <van-checkbox-group
        v-model="selectList"
        ref="checkboxGroup"
        class="cartList"
      >
        <van-checkbox
          :name="item.id"
          class="item"
          v-for="item in cartList.valid"
          :key="item.id"
          checked-color="#25c9c3"
        >
          <div class="card">
            <div
              class="img"
              @click.stop="$router.push('/detail/' + item.productInfo.id)"
            >
              <img :src="item.productInfo.image" />
              <div class="tag">
                <span>{{
                  `库存${$options.filters.formatNum(
                    item.productInfo.attrInfo.stock
                  )}${item.productInfo.unit_name}`
                }}</span>
              </div>
            </div>
            <div class="info">
              <div class="info_t">
                <div class="title">{{ item.productInfo.store_name }}</div>
                <div class="suk">
                  {{ `规格：${item.productInfo.attrInfo.suk}` }}
                </div>
              </div>
              <div class="info_b">
                <div class="info_bl">
                  <div class="price">
                    ¥<span>{{ item.truePrice | formatPrice(0) }}</span
                    >.{{ item.truePrice | formatPrice(1) }}
                  </div>
                  <div class="orPrice">¥ {{ item.productInfo.ot_price }}</div>
                </div>
                <div class="info_br" @click.stop.prevent>
                  <van-stepper
                    :value="item.cart_num"
                    theme="round"
                    :max="item.productInfo.attrInfo.stock"
                    @change="changeNum"
                    :name="item.id"
                  />
                </div>
              </div>
            </div>
          </div>
        </van-checkbox>
      </van-checkbox-group>
    </van-pull-refresh>
    <div
      class="bottom"
      v-if="
        cartList && (cartList.valid.length != 0 || cartList.invalid.length != 0)
      "
    >
      <div class="bottom_l">
        <van-checkbox
          class="selectAll"
          :value="selectAll"
          checked-color="#25c9c3"
          @click="$refs['checkboxGroup'].toggleAll(!selectAll)"
          v-if="cartList.valid.length > 0"
          >{{ selectAll ? "全不选" : "全选"
          }}<span>{{ `(${selectList.length})` }}</span></van-checkbox
        >
      </div>
      <div class="bottom_r">
        <template v-if="!deleteFlag && cartList.valid.length > 0">
          <div class="totalPrice">¥{{ totalPrice }}</div>
          <van-button round color="#25c9c3" class="btn" @click="orderConfirm"
            >立即下单</van-button
          >
        </template>
        <van-button
          round
          color="#25c9c3"
          class="btn"
          plain
          @click="deleteInvalid"
          v-if="
            (deleteFlag || cartList.valid.length == 0) &&
            cartList.invalid.length > 0
          "
          >清空失效商品</van-button
        >
        <van-button
          round
          color="#25c9c3"
          class="btn"
          @click="deleteSelect"
          v-if="deleteFlag && cartList.valid.length > 0"
          >删除所选</van-button
        >
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapMutations } from "vuex";
export default {
  name: "Cart",
  data() {
    return {
      isLoading: false,
      selectList: [],
      activeNames: [],
      swiperOption_invalid: {
        slidesPerView: "auto",
        direction: "horizontal",
        freeMode: true,
        freeModeMomentumRatio: 0.5,
      },
      deleteFlag: false,
    };
  },
  computed: {
    ...mapGetters(["cartList"]),
    selectAll() {
      return (
        this.cartList && this.selectList.length == this.cartList.valid.length
      );
    },
    totalPrice() {
      let price = 0;
      this.selectList.map((id) => {
        this.cartList.valid.map((item) => {
          if (item.id == id) price += item.truePrice * item.cart_num;
        });
      });
      return price.toFixed(2);
    },
  },
  filters: {
    formatNum(value) {
      return value > 10000
        ? (value / 10000).toFixed(1).replace(/\.0$/, "") + "w"
        : value > 1000
        ? (value / 1000).toFixed(1).replace(/\.0$/, "") + "k"
        : value;
    },
    formatPrice(value, i) {
      return parseFloat(value).toFixed(2).split(".")[i];
    },
  },
  activated() {
    this.getCartList();
    this.deleteFlag = false;
  },
  methods: {
    ...mapMutations(["changeLoading", "changeCartNum"]),
    getCartList(callback) {
      this.changeLoading(true);
      this.$axios.get("/api/cart/list").then((d) => {
        this.changeLoading(false);
        console.log("cart", d.data);
        if (d.data.status == 200) {
          this.$store.commit("saveCartInfo", d.data.data);
        } else if (d.data.status == 410000) {
          this.$toast.fail("请重新登录");
          this.$store.commit("loginOut");
          this.$router.push("/login");
        }
        if (callback) callback();
      });
    },
    onRefresh() {
      this.getCartList(() => {
        this.isLoading = false;
      });
    },
    changeNum(number, { name: id }) {
      clearTimeout(this["timer" + id]);
      this["timer" + id] = setTimeout(() => {
        let param = { id, number };
        this.$axios.post("/api/cart/num", param).then((d) => {
          console.log("cart/num", d.data);
          if (d.data.status == 200) {
            this.changeCartNum(param);
          } else if (d.data.status == 400) {
            this.getCartList();
          } else if (d.data.status == 410000) {
            this.$toast.fail("请重新登录");
            this.$store.commit("loginOut");
            this.$router.push("/login");
          }
        });
      }, 200);
    },
    deleteCart(ids) {
      this.$toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true,
        message: "删除中...",
      });
      this.$axios
        .post("/api/cart/del", {
          ids,
        })
        .then((d) => {
          console.log("cart/del", d.data);
          this.$toast.clear();
          if (d.data.status == 200) {
            this.$toast.success("删除成功");
            this.getCartList();
          } else if (d.data.status == 410000) {
            this.$toast.fail("请重新登录");
            this.$store.commit("loginOut");
            this.$router.push("/login");
          }
        })
        .catch(() => {
          this.$toast.clear();
          this.$toast.fail("请求失败");
        });
    },
    deleteSelect() {
      if (!this.selectList || this.selectList.length == 0) {
        this.$toast("请选择商品");
      } else {
        this.deleteCart(this.selectList);
      }
    },
    deleteInvalid() {
      if (!this.cartList || this.cartList.invalid.length == 0) return;
      var ids = [];
      this.cartList.invalid.map((item) => {
        ids.push(item.id);
      });
      this.deleteCart(ids);
    },
    orderConfirm() {
      if (!this.selectList || this.selectList.length == 0) {
        this.$toast("请选择商品");
      } else {
        let cartId = this.selectList.join(",");
        this.$router.push(`/order/confirm/${cartId}`);
      }
    },
  },
};
</script>

<style lang="less" scoped>
.cart {
  .top {
    position: fixed;
    top: 0;
    left: 0;
    z-index: 99;
    height: 56px;
    width: 100%;
    padding: 0 10px;
    box-sizing: border-box;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    font-size: 15px;
    background: #fff;
    .title {
      font-size: 17px;
      font-weight: bold;
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
    }
    .rightBtn {
      padding: 3px 10px;
      &:active {
        background: #f2f3f5;
      }
    }
  }
  .content {
    min-height: calc(100vh - 156px);
    margin-top: 56px;
    margin-bottom: 50px;
    .invalidList {
      .collapseTitle {
        line-height: 24px;
        display: flex;
        align-items: center;
        .van-icon {
          margin-left: 5px;
          color: red;
        }
      }
      .swiper {
        .swiper-slide {
          margin-right: 10px;
          width: auto !important;
          .invalidItem {
            width: 88px;
            background: #fff;
            border-radius: 10px 10px 0 0;
            border-bottom: 1px solid rgba(0, 0, 0, 0.2);
            overflow: hidden;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.05);
            &:active {
              background: #f2f3f5;
            }
            .img {
              width: 100%;
              height: 0;
              padding-bottom: 100%;
              position: relative;
              img {
                width: 100%;
                height: 100%;
                position: absolute;
              }
            }
            .info {
              padding: 5px;
              padding-bottom: 1px;
              font-size: 12px;
              color: #333;
              .title {
                line-height: 16px;
                font-weight: 500;
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
              }
              .info_b {
                display: flex;
                justify-content: space-between;
                align-items: flex-end;
                .price {
                  font-family: Avenir-Heavy, PingFang SC, Helvetica Neue, Arial,
                    sans-serif;
                  font-weight: 500;
                  transform: scale(0.9);
                  transform-origin: left bottom;
                  color: #666;
                  span {
                    font-size: 14px;
                  }
                }
                .num {
                  color: #969799;
                }
              }
            }
          }
        }
      }
    }
    .cartList {
      margin: 15px 0;
      .item {
        background-color: #fff;
        padding-left: 15px;
        &:not(:last-of-type) {
          .card {
            border-bottom: 1px solid #f5f5f5;
          }
        }
        &:active {
          background: #f2f3f5;
        }
        ::v-deep.van-checkbox__label {
          flex: 1;
        }
        .card {
          position: relative;
          box-sizing: border-box;
          padding: 13px 16px;
          padding-left: 10px;
          font-size: 12px;
          display: flex;
          .img {
            position: relative;
            flex-shrink: 0;
            width: 88px;
            height: 88px;
            margin-right: 8px;
            overflow: hidden;
            img {
              width: 100%;
              height: 100%;
              border-radius: 8px;
            }
            .tag {
              position: absolute;
              height: 20px;
              top: 2px;
              left: 0;
              display: flex;
              align-items: center;
              white-space: nowrap;
              span {
                background: #25c9c3;
                opacity: 0.9;
                border-radius: 0 8px 8px 0;
                position: relative;
                padding-left: 4px;
                padding-right: 6px;
                color: #fff;
                line-height: 16px;
              }
            }
          }
          .info {
            flex: 1;
            width: 0;
            height: 88px;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            .info_t {
              .title {
                line-height: 16px;
                font-weight: 500;
                display: -webkit-box;
                overflow: hidden;
                text-overflow: ellipsis;
                -webkit-line-clamp: 2;
                -webkit-box-orient: vertical;
              }
              .suk {
                color: #646566;
                line-height: 20px;
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
              }
            }
            .info_b {
              height: 20px;
              display: flex;
              justify-content: space-between;
              .info_bl {
                flex: 1;
                width: 0;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
                .price {
                  display: inline-block;
                  color: #323233;
                  font-family: Avenir-Heavy, PingFang SC, Helvetica Neue, Arial,
                    sans-serif;
                  font-weight: 500;
                  span {
                    font-size: 16px;
                  }
                }
                .orPrice {
                  display: inline-block;
                  margin-left: 5px;
                  color: #969799;
                  text-decoration: line-through;
                }
              }
              .info_br {
                flex-shrink: 0;
                ::v-deep button {
                  width: 20px;
                  height: 20px;
                  &.van-stepper__minus {
                    color: #25c9c3;
                    border-color: #25c9c3;
                  }
                  &.van-stepper__plus {
                    background-color: #25c9c3;
                  }
                }
                ::v-deep input {
                  height: 20px;
                  width: 25px;
                }
              }
            }
          }
        }
      }
    }
  }
  .bottom {
    position: fixed;
    bottom: 1.33333rem;
    left: 0;
    width: 100%;
    height: 50px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 15px;
    box-sizing: border-box;
    background: #fff;
    border-top: 1px solid #f5f5f5;
    border-bottom: 1px solid #f5f5f5;
    .bottom_l {
      .selectAll {
        font-size: 14px;
        ::v-deep .van-checkbox__label {
          span {
            font-size: 12px;
            color: #666;
          }
        }
      }
    }
    .bottom_r {
      display: flex;
      align-items: center;
      .totalPrice {
        font-size: 18px;
        color: #25c9c3;
      }
      .btn {
        height: 30px;
        margin-left: 15px;
      }
    }
  }
}
</style>